﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace MyPaint
{
    public partial class FrmSettings : Form
    {
        private Timer timerForTakeMousePos;

        public FrmSettings()
        {
            InitializeComponent();

            this.ShowInTaskbar = false;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            check_appAutoStart.Checked = bool.Parse(config.AppSettings.Settings["appAutoStart"].Value);
            tip_appAutoStart.Text = check_appAutoStart.Checked ? "开启" : "关闭";

            check_isExitToMiniMode.Checked = bool.Parse(config.AppSettings.Settings["isExitToMiniMode"].Value);
            tip_isExitToMiniMode.Text = check_isExitToMiniMode.Checked ? "最小化到系统托盘" : "退出程序";

            check_createDeskShortCut.Checked = bool.Parse(config.AppSettings.Settings["createDeskShortCut"].Value);
            tip_createDeskShortCut.Text = check_createDeskShortCut.Checked ? "已创建" : "未创建（如更新，可重新生成）";
        }

        public FrmSettings(Form frmMain) : this()
        {
            this.Height = frmMain.Height;//出现在主窗体右侧，并等高显示
            Point p = new Point(frmMain.Location.X + frmMain.Width, frmMain.Location.Y);
            Size s = Screen.PrimaryScreen.Bounds.Size;
            p.X = p.X > s.Width - this.Width ? s.Width - this.Width : p.X;
            this.Location = p;//左右边的间距不够，就取屏幕与控件的宽度差

            timerForTakeMousePos = new Timer();
            timerForTakeMousePos.Interval = 50;//0.05秒
            timerForTakeMousePos.Tick += new EventHandler(time_Tick);
            timerForTakeMousePos.Start();

            //设置关闭时程序最小化
            check_isExitToMiniMode.Click += (sender, e) =>
            {
                tip_isExitToMiniMode.Text = check_isExitToMiniMode.Checked ? "最小化到系统托盘" : "退出程序";

                //修改配置文件
                UpdateAppSettingsConfig("isExitToMiniMode", check_isExitToMiniMode.Checked.ToString());
            };

            //设置开机自启动
            check_appAutoStart.Click += (sender, e) =>
            {
                tip_appAutoStart.Text = check_appAutoStart.Checked ? "开启" : "关闭";

                string sourseEXE = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "绘图工具.exe");
                string startup_ShortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\绘图工具.lnk";
                if (check_appAutoStart.Checked)//需要创建开机自启动目录快捷键
                {
                    if (File.Exists(startup_ShortcutPath))
                    {
                        File.Delete(startup_ShortcutPath);
                    }
                    _ = CreateShortcut(sourseEXE, startup_ShortcutPath);
                }
                else
                {
                    if (File.Exists(startup_ShortcutPath))
                    {
                        File.Delete(startup_ShortcutPath);
                    }
                }

                //修改配置文件
                UpdateAppSettingsConfig("appAutoStart", check_appAutoStart.Checked.ToString());

            };

            //设置程序创建桌面快捷方式
            check_createDeskShortCut.Click += (sender, e) =>
            {
                tip_createDeskShortCut.Text = check_createDeskShortCut.Checked ? "已创建" : "未创建（如更新，可重新生成）";

                string sourseEXE = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "绘图工具.exe");
                string Desktop_ShortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\绘图工具.lnk";
                if (check_createDeskShortCut.Checked)//需要创建桌面快捷键
                {
                    if (File.Exists(Desktop_ShortcutPath))
                    {
                        File.Delete(Desktop_ShortcutPath);
                    }
                    _ = CreateShortcut(sourseEXE, Desktop_ShortcutPath);
                }
                else
                {
                    if (File.Exists(Desktop_ShortcutPath))
                    {
                        File.Delete(Desktop_ShortcutPath);
                    }
                }

                //修改配置文件
                UpdateAppSettingsConfig("createDeskShortCut", check_createDeskShortCut.Checked.ToString());
            };
        }

        /// <summary>
        /// 创建一个快捷方式(用户级别)
        /// </summary>
        /// <param name="targetPath">目标程序路径.exe</param>
        /// <param name="shortcutPath">快捷方式放置路径.lnk</param>
        private object CreateShortcut(string targetPath, string shortcutPath)
        {
            try
            {
                var shellType = Type.GetTypeFromProgID("WScript.Shell");
                dynamic shell = Activator.CreateInstance(shellType);
                var shortcut = shell.CreateShortcut(shortcutPath);
                shortcut.TargetPath = targetPath;
                //shortcut.Arguments = "在路径后面追加的参数 空格分隔";
                //shortcut.Description = "备注信息";
                //shortcut.WindowStyle = FormWindowState.Normal;
                //shortcut.IconLocation = "图标路径";

                shortcut.Save();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void UpdateAppSettingsConfig(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //修改配置文件
            config.AppSettings.Settings[key].Value = value;
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("AppSettings");
        }

        private void time_Tick(object sender, EventArgs e)
        {
            Point p = Control.MousePosition;
            MouseButtons click = Control.MouseButtons;

            bool IsInSettingArea = this.Bounds.Contains(p.X, p.Y);

            if (!IsInSettingArea && (click == MouseButtons.Left || click == MouseButtons.Right || click == MouseButtons.Middle))
            {
                this.timerForTakeMousePos.Stop();
                this.Close();
                this.Dispose();
            }
        }
    }
}
